package com.bgh.dynobot;

import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

public class Vehicles extends Activity implements OnClickListener {
	
	private DynoDbAdapter DbHelper;
	private TextView tv = null;
	private ImageView iv = null;
	public String currentVehicle;
	public int currentVehicleID;
	
	private ViewFlipper viewFlipper;
	private Animation slideLeftIn;
	private Animation slideLeftOut;
	private Animation slideRightIn;
    private Animation slideRightOut;
    
    private Button CreateButton = null;
	private Button CancelButton = null;
	
	private EditText et = null;
	private Spinner sp = null;	
	public String vehicleName, vehicleDesc, vehicleWeight, weightUnit, vehiclePicURI = null;
    
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);   
        setContentView(R.layout.vehicles);
        
        PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
 		SharedPreferences appPreferences = PreferenceManager.getDefaultSharedPreferences(this);
 		currentVehicle = appPreferences.getString("current_vehicle", "Default vehicle");
 		currentVehicleID = appPreferences.getInt("current_vehicle_id",0);
 		viewFlipper = (ViewFlipper)findViewById(R.id.vehicle_flipper);
 		displayVehicle(currentVehicle);
 		slideLeftIn = AnimationUtils.loadAnimation(this, R.anim.slide_left_in);
        slideLeftOut = AnimationUtils.loadAnimation(this, R.anim.slide_left_out);
        slideRightIn = AnimationUtils.loadAnimation(this, R.anim.slide_right_in);
        slideRightOut = AnimationUtils.loadAnimation(this, R.anim.slide_right_out); 
        
        
        
        //**********Create Vehicle***********
        CreateButton = (Button) findViewById(R.id.createVehicle);
        CreateButton.setOnClickListener(this);        
        CancelButton = (Button) findViewById(R.id.cancelVehicle);
        CancelButton.setOnClickListener(this);
        
        Spinner spinner = (Spinner) this.findViewById(R.id.editWeightUnit);        
        ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(
                        this, android.R.layout.simple_spinner_item);
 
        adapter.add("Kilograms");
        adapter.add("Pounds");
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        
        ImageView image =  (ImageView)this.findViewById(R.id.vehiclePic);
        Uri imageUri = Uri.parse("/sdcard/media/pics/Ute/ute2.JPG");          
        image.setImageURI(imageUri);     
         
        TextView tv =  (TextView)this.findViewById(R.id.vehiclePicURI);
        tv.setText("/sdcard/media/pics/Ute/ute2.JPG");          
        tv.setVisibility(0);
        tv.setHeight(0); 
 		
    }
	
	public void displayVehicle(String vehicleName){
		DbHelper = new DynoDbAdapter(this);
	    DbHelper.open();
	    
	    Cursor c = DbHelper.fetchVehicle(vehicleName);
	    if (c.moveToFirst()) {
	    	currentVehicle = c.getString(c.getColumnIndex(DynoDbAdapter.KEY_NAME));
	    	currentVehicleID = c.getInt(c.getColumnIndex(DynoDbAdapter.KEY_VEHICLE_ID));
    		tv = (TextView) findViewById(R.id.vehicleName);
    		tv.setText(currentVehicle);
    		tv = (TextView) findViewById(R.id.vehicleDesc);
    		tv.setText(c.getString(c.getColumnIndex(DynoDbAdapter.KEY_DESC)));
    		tv = (TextView) findViewById(R.id.vehicleWeight);
    		tv.setText(c.getString(c.getColumnIndex(DynoDbAdapter.KEY_WEIGHT)) + " " + 
    				c.getString(c.getColumnIndex(DynoDbAdapter.KEY_WEIGHT_UNIT)));
    		tv = (TextView) findViewById(R.id.numberOfTimedRuns);
    		tv.setText("Timed runs: " + "0");
    		tv = (TextView) findViewById(R.id.fastestRun);
    		tv.setText("Fastest run: " + "0 seconds @ 0kmph");
    		tv = (TextView) findViewById(R.id.averageRun);
    		tv.setText("Average run: " + "0 seconds @ 0kmph");
    		          
    		iv = (ImageView) findViewById(R.id.vehiclePic);
    		Uri imageUri = Uri.parse("/sdcard/media/pics/Ute/ute2.JPG");
    		iv.setImageURI(imageUri);     
    		
    		PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
     		SharedPreferences appPreferences = PreferenceManager.getDefaultSharedPreferences(this);
     		SharedPreferences.Editor editor = appPreferences.edit();
            editor.putString("current_vehicle", currentVehicle);
            editor.putInt("current_vehicle_id", currentVehicleID);
            editor.commit();
	    }
	    
	    c.close();
	    DbHelper.close();
	}
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	boolean result = super.onCreateOptionsMenu(menu);
        menu.add(0, 0, 0, "Change vehicle");
        menu.add(0, 1, 0, "Delete vehicle");
        return result;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch (item.getItemId()) {
	        case 0:
	        	DbHelper = new DynoDbAdapter(this);
			    DbHelper.open();
			    
			    Cursor c = DbHelper.fetchAllVehicles();
				
			    final ArrayList<String> vehicleList = new ArrayList<String>();

			    	vehicleList.add("Create new vehicle");
			       if (c.moveToFirst()) {
			    	   do{
			    		   vehicleList.add(c.getString(c.getColumnIndex(DynoDbAdapter.KEY_NAME)));
			    	   } while (c.moveToNext());
			       }	
			       
			       final String[] items = (String[]) vehicleList.toArray(new String[0]);

				    AlertDialog.Builder builder = new AlertDialog.Builder(this);
				    builder.setTitle("Choose vehicle");
				    builder.setItems(items, new DialogInterface.OnClickListener() {
			        public void onClick(DialogInterface dialog, int selection) {
			        	if (selection == 0) {	
			        		viewFlipper.setInAnimation(slideLeftIn);
			                viewFlipper.setOutAnimation(slideLeftOut);
			        		viewFlipper.showNext();			        	     
			        	}else{
			        		displayVehicle(vehicleList.get(selection));
			        	}

			        }
			    });
			    AlertDialog alert = builder.create();
			    alert.show();
		        
		        c.close();
			    DbHelper.close();
			    return true;
	        case 1:
	        	AlertDialog.Builder deleteAlert = new AlertDialog.Builder(this);  
			     
				   //alert.setTitle("Title");  
	        	deleteAlert.setMessage("Delete vehicle " + currentVehicle);  
				     
				   
	        	deleteAlert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {  
				  public void onClick(DialogInterface dialog, int whichButton) {  
					  DbHelper = new DynoDbAdapter(Vehicles.this);
					    DbHelper.open();		    
					    boolean success = DbHelper.deleteVehicle(currentVehicle);
					    DbHelper.close();
					    Toast.makeText(Vehicles.this, currentVehicle + " deleted", Toast.LENGTH_LONG).show();
					    displayVehicle("Default vehicle");
				    }  
				  });  
				    
	        	deleteAlert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {  
				    public void onClick(DialogInterface dialog, int whichButton) {  
				      // Canceled.  
				    }  
				  });  
				    
	        	deleteAlert.show();  
	        	return true;
        }
        return super.onOptionsItemSelected(item);
    }

	public void onClick(View v) {
		if (v == CreateButton) {
			
			et = (EditText) this.findViewById(R.id.editName);
			vehicleName = et.getText().toString();
			
			et = (EditText) this.findViewById(R.id.editDesc);
			vehicleDesc = et.getText().toString();
			
			et = (EditText) this.findViewById(R.id.editWeight);
			vehicleWeight = et.getText().toString();
			
			sp = (Spinner) this.findViewById(R.id.editWeightUnit);
			weightUnit = (String)sp.getSelectedItem();
			
			TextView tv =  (TextView)this.findViewById(R.id.vehiclePicURI);
	        vehiclePicURI = (String) tv.getText();         
			
			DbHelper = new DynoDbAdapter(this);
	        DbHelper.open();
	        DbHelper.insertVehicle(vehicleName, vehicleDesc, Integer.parseInt(vehicleWeight), weightUnit, vehiclePicURI);
	        Toast.makeText(this, "Vehicle created", Toast.LENGTH_LONG).show();
	        DbHelper.close();
		}
		
		if(v == CancelButton){
			viewFlipper.setInAnimation(slideRightIn);
            viewFlipper.setOutAnimation(slideRightOut);
    		viewFlipper.showNext();	
		}
	}
}
